package com.chat.controller;

import com.chat.entity.User;
import com.chat.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "*")
public class UserController {
    
    @Autowired
    private UserRepository userRepository;
    
    /**
     * 用户登录/注册
     * 如果用户名存在则登录，不存在则自动注册
     */
    @PostMapping("/login")
    public ResponseEntity<?> loginOrRegister(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        
        if (username == null || username.trim().isEmpty()) {
            return ResponseEntity.badRequest().body("用户名不能为空");
        }
        
        username = username.trim();
        
        if (username.length() < 2) {
            return ResponseEntity.badRequest().body("用户名至少2个字符");
        }
        
        // 查找用户
        Optional<User> existingUser = userRepository.findByUsername(username);
        
        User user;
        if (existingUser.isPresent()) {
            // 用户存在，更新最后登录时间
            user = existingUser.get();
            user.setLastLogin(LocalDateTime.now());
            userRepository.save(user);
        } else {
            // 用户不存在，创建新用户
            user = new User(username);
            userRepository.save(user);
        }
        
        // 返回用户信息
        Map<String, Object> response = new HashMap<>();
        response.put("id", user.getId().toString());
        response.put("username", user.getUsername());
        response.put("createdAt", user.getCreatedAt());
        response.put("lastLogin", user.getLastLogin());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取所有用户列表
     */
    @GetMapping("/list")
    public ResponseEntity<List<User>> getUserList() {
        List<User> users = userRepository.findAll();
        return ResponseEntity.ok(users);
    }
    
    /**
     * 根据ID获取用户信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getUserById(@PathVariable Long id) {
        Optional<User> user = userRepository.findById(id);
        
        if (user.isPresent()) {
            return ResponseEntity.ok(user.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 根据用户名获取用户信息
     */
    @GetMapping("/username/{username}")
    public ResponseEntity<?> getUserByUsername(@PathVariable String username) {
        Optional<User> user = userRepository.findByUsername(username);
        
        if (user.isPresent()) {
            return ResponseEntity.ok(user.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}

